<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);
class user{
    function __construct() {
		$this->http_user_agent = $_SERVER['HTTP_USER_AGENT'];
		$this->db = pc_base::load_model('member_model');
		$this->ssodb = pc_base::load_model('sso_members_model');
		$this->siteid = get_siteid();
		$this->config = getcache('iapp', 'commons');
		$this->upload_url = pc_base::load_config('system','upload_url');
    }

	public function init(){
		print_r($this->config);
	}
	
	public function login(){
		$re = array();
		$this->_session_start();
		
		$username = trim($_POST['username']) ? trim($_POST['username']) : null;
		$password = trim($_POST['password']) ? trim($_POST['password']) : null;
		$cookietime = intval($_POST['cookietime']);
			
		$user = $this->db->get_one(array('username'=>$username));
		
		if($user){
			$password = md5(md5(trim($password)).$user['encrypt']);
			if($user['password'] == $password) {
		
				$cookietime = $cookietime ? cookietime: 0;
				
				$phpcms_auth_key = md5(pc_base::load_config('system', 'auth_key').$this->http_user_agent);
				$phpcms_auth = sys_auth($user[userid]."\t".$password, 'ENCODE', $phpcms_auth_key);
					
				param::set_cookie('auth', $phpcms_auth, $cookietime);
				param::set_cookie('_userid', $user[userid], $cookietime);
				param::set_cookie('_username', $user[username], $cookietime);
				param::set_cookie('_groupid', $user[groupid], $cookietime);
				
				$nickname = empty($user['nickname']) ? '网友' : $user['nickname'];
				param::set_cookie('_nickname', $nickname, $cookietime);
				
				$iappshare_db = pc_base::load_model('iappShare_model');
				$iappshare = $iappshare_db->select(array('userid'=>$user[userid]),'id,userid,name,connectid');
				
				$data = array(
							"userid"=>$user[userid],
						    "nick"=>$nickname,
						    "acctoken"=>$password,
						    "mobile"=>$user[mobile],
						    "integral"=>$user[point],
						    "share"=>$iappshare);
				
				$re['success'] = 'OK';
				$re['msg'] = '登录成功~';
				$re['data'] = $data;
			}else{
				$re['success'] = 'ERRPWD';
				$re['msg'] = '密码错误~';
			}
		}else{
			$re['success'] = 'NOUSERNAME';
			$re['msg'] = '用户不存在~';
		}
		echo json_encode($re);
    }
	
	public function tp_login() {
		
		$params = $_GET;
		$type = $params['type'];
		$re = array();
		session_start();
		
		$oneuser = $this->db->select('','*',1,'userid DESC');
		$oneuserid = $oneuser[0][userid] +1000;
		
		switch ($type)
		{
			case "qqweibo":
				pc_base::load_app_class('Tencent', '', 0);
				$client_id = pc_base::load_config('system', 'qq_akey');
				$client_secret = pc_base::load_config('system', 'qq_skey');
				OAuth::init($client_id, $client_secret);

				//验证授权
				$_userdata = json_decode(Tencent::api('user/info',array('access_token'=>$params['access_token'],'openid'=>$params['openid'])), true);
				
				$userid =0;
				if ($_userdata['data']['name']) {
					$ud = $this->db->get_one(array('connectid'=>$_userdata[data][openid]));
					if($ud){
						$userid=$ud[userid];
					}else{
						$info = array();	
						$info[username] = $oneuserid;
						$info[password] = random(8);
						$info[email] = $oneuserid.'@noemail.com';
						$info[nickname] = $_userdata[data][nick];
						$info[connectid] = $_userdata[data][openid];
						$info[from] = 'qqweibo';
						$info[regip] = ip();
						
						$this->_init_phpsso();
						$status = $this->client->ps_member_register($info['username'], $info['password'],$info['email'], $info['regip']);
						
						if($status > 0) {
							unset($info[pwdconfirm]);
							$info['phpssouid'] = $status;
							$memberinfo = $this->client->ps_get_member_info($status);
							$memberinfo = unserialize($memberinfo);
							$info['encrypt'] = $memberinfo['random'];
							$info['password'] = password($info['password'], $info['encrypt']);
							$info['regdate'] = $info['lastdate'] = SYS_TIME;
							$insert_id = $this->db->insert($info,true);
							$userid=$insert_id;
						}
					}
					
					if($userid){	
						$userdata = $this->db->get_one(array('userid'=>$userid));
						$cookietime = $cookietime ? cookietime: 0;
						$nickname = $userdata['nickname']=="" ? '网友' : $userdata['nickname'];
						
						$phpcms_auth_key = md5(pc_base::load_config('system', 'auth_key').$this->http_user_agent);
						$phpcms_auth = sys_auth($userdata[userid]."\t".$password, 'ENCODE', $phpcms_auth_key);
							
						param::set_cookie('auth', $phpcms_auth, $cookietime);
						param::set_cookie('_userid', $userdata[userid], $cookietime);
						param::set_cookie('_username', $userdata[username], $cookietime);
						param::set_cookie('_groupid', $userdata[groupid], $cookietime);
						param::set_cookie('_nickname', $nickname, $cookietime);
						
						$iappshare_db = pc_base::load_model('iappShare_model');
						$iappshare = $iappshare_db->select(array('userid'=>$userid),'id,userid,name,connectid');
						
						$re[success]="OK";
						$re[msg]="登录成功";
						$re[data]=array(
								'userid'=>$userdata[userid],
								'nick'=>$nickname,
								'acctoken'=>$userdata[password],
								'mobile'=>$userdata[mobile],
								"integral"=>$userdata[point],
								'share'=>$iappshare
								);
					}else{
						$re[data]="";
						$re[success]="ERR";
						$re[msg]="登录失败";
					}	
				}else{
					$re['success'] = 'ERR';
					$re['msg'] = '登录失败~';
				}
				break; 
			case "qzone":
				echo "qzone";
				break;
			case "sina":
				pc_base::load_app_class('sinaweibo', '', 0);
				$WB_AKEY = pc_base::load_config('system', 'sina_akey');
				$WB_SKEY = pc_base::load_config('system', 'sina_skey');
				$SaeTOAuthV2 = new SaeTOAuthV2(WB_AKEY , WB_SKEY);

				$token = array('access_token' => $params[access_token],
							   'remind_in' => $params[remind_in],
							   'expires_in' => $params[expires_in],
							   'uid' => $params[uid]
							  );
			
				if($token[access_token] !='' && $token[remind_in] !='' && $token[expires_in] !='' && $token[uid] !='')
				{
					$_SESSION['token'] = $token;
					setcookie('weibojs_'.$SaeTOAuthV2->client_id, http_build_query($token));
					
					$SaeTClientV2 = new SaeTClientV2(WB_AKEY , WB_SKEY , $token['access_token']);
					$uid_get = $SaeTClientV2->get_uid();
					$uid = $uid_get['uid'];
					$_userdata = $SaeTClientV2->show_user_by_id($uid);
					
					if($_userdata[id]>0){
						$userid = 0;
						$ud = $this->db->get_one(array('connectid'=>$token[access_token]));
						if($ud){
							$userid=$ud[userid];
						}else{
							$info = array();	
							$info[username] = $oneuserid;
							$info[password] = random(8);
							$info[email] = $oneuserid.'@noemail.com';
							$info[nickname] = $_userdata[screen_name];
							$info[connectid] = $token[access_token];
							$info[from] = 'sina';
							$info[regip] = ip();
							
							$this->_init_phpsso();
							$status = $this->client->ps_member_register($info['username'], $info['password'],$info['email'], $info['regip']);
							
							if($status > 0) {
								unset($info[pwdconfirm]);
								$info['phpssouid'] = $status;
								$memberinfo = $this->client->ps_get_member_info($status);
								$memberinfo = unserialize($memberinfo);
								$info['encrypt'] = $memberinfo['random'];
								$info['password'] = password($info['password'], $info['encrypt']);
								$info['regdate'] = $info['lastdate'] = SYS_TIME;
								$insert_id = $this->db->insert($info,true);
								
								//修改用户名
								$newusername = $insert_id + 1000;
								$this->db->update(array("username"=>$newusername),array('userid'=>$insert_id));
								$userid=$insert_id;
							}
						}
						
						if($userid){	
							$userdata = $this->db->get_one(array('userid'=>$userid));
							
							$cookietime = $cookietime ? cookietime: 0;
							$nickname = $userdata['nickname']=="" ? '网友' : $userdata['nickname'];
							
							$phpcms_auth_key = md5(pc_base::load_config('system', 'auth_key').$this->http_user_agent);
							$phpcms_auth = sys_auth($userdata[userid]."\t".$password, 'ENCODE', $phpcms_auth_key);
								
							param::set_cookie('auth', $phpcms_auth, $cookietime);
							param::set_cookie('_userid', $userdata[userid], $cookietime);
							param::set_cookie('_username', $userdata[username], $cookietime);
							param::set_cookie('_groupid', $userdata[groupid], $cookietime);
							param::set_cookie('_nickname', $nickname, $cookietime);
							
							$iappshare_db = pc_base::load_model('iappShare_model');
							$iappshare = $iappshare_db->select(array('userid'=>$userid),'id,userid,name,connectid');
							
							$re[success]="OK";
							$re[msg]="登录成功";
							$re[data]=array(
								'userid'=>$userdata[userid],
								'nick'=>$nickname,
								'acctoken'=>$userdata[password],
								'mobile'=>$userdata[mobile],
								"integral"=>$userdata[point],
								'share'=>$iappshare
								);
						}else{
							$re[data]="";
							$re[success]="ERR";
							$re[msg]="登录失败";
						}
					}else{
						$re['success'] = 'ERR';
						$re['msg'] = '登录失败~';
					}
				}else{
					$re['success'] = 'ERR';
					$re['msg'] = '登录失败,授权数据不完整~';
				}
				break;
			default:
				$re['success'] = 'ERR';
				$re['msg'] = 'type错误~';
		}
		echo json_encode($re);
	}
	
	/*
	public function userinfo(){
		$userid = isset($_GET['userid']) && trim($_GET['userid']) ? trim($_GET['userid']) :null;
		
		if($userid){
			$userdata = $this->db->get_one(array('userid'=>$userid));
			print_r($userdata);
		}
	}
	*/
	
	public function userdata(){
		$userid = isset($_GET['userid']) && trim($_GET['userid']) ? trim($_GET['userid']) :null;
		$acctoken = isset($_GET['acctoken']) && trim($_GET['acctoken']) ? trim($_GET['acctoken']) :null;
		if($userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			$data = array();
			if($userdata){
				$data[success]='OK';
				$data[data]=array(
							'username'=>$userdata[username],
							'nickname'=>$userdata[nickname],
							'sex'=>$userdata[sex],
							'area'=>$userdata[area],
							'mobile'=>$userdata[mobile],
							'address'=>$userdata[address],
							'email'=>$userdata[email],
							'point'=>$userdata[point],
							'regdate'=>date('Y-m-d', $userdata[regdate])
						);
				//$data[data] = $userdata;
				$data[msg]='加载成功~';
			}else{
				$data[success]='NOLOGIN';
				$data[msg]='没有登录~';
			}
		}else{
			$data[success]='ERR';
			$data[msg]='参数错误~';
		}
		echo json_encode($data);
	}
	/**
	 * 修改用户资料
	 */
	public function useredit(){
		$userid = isset($_GET['userid']) ? trim($_GET['userid']) : exit('0');
		$acctoken = isset($_GET['acctoken']) ? trim($_GET['acctoken']) : exit('0');
		$nickname = isset($_POST['nickname']) ? trim($_POST['nickname']) : exit('0');
		
		$re =array();
		$username = param::get_cookie('_username');
		if($username){
			$return_id = $this->db->update(array("nickname"=>$nickname),array('userid'=>$userid));
			if($return_id){
				$re["success"]="OK";
				$re["msg"]="修改成功";
			}else{
				$re["success"]="ERR";
				$re["msg"]="修改失败";
			}
		}else{
			$re["success"]="NOLOGIN";
			$re["msg"]="没有登录";
		}
		echo json_encode($re);
		
	}
	
	/**
	 * 修改头像
	 */
	public function avatar(){
	
		$userid = isset($_GET['userid']) && trim($_GET['userid']) ? trim($_GET['userid']) : null;
		$acctoken = isset($_GET['acctoken']) && trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		$re = array();
		
		if($userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			$phpssouid = $userdata[phpssouid];
			if($userdata){
			
				if(fileext($_FILES["avatardata"]["name"])=='jpg'){
					$siteinfo = getcache('sitelist', 'commons');
					$site_setting = string2array($siteinfo[$this->siteid]['setting']);
					if($_FILES["avatardata"]["size"] < $site_setting['upload_maxsize']*1024){
						if($_FILES["avatardata"]["error"] > 0){
							$re['success'] = 'ERR';
							$re['msg'] = '未知上传错误|1';
						}else{
							//创建图片存储文件夹
							$dir1 = ceil($phpssouid / 10000);
							$dir2 = ceil($phpssouid % 10000 / 1000);
							$avatarfile = PHPCMS_PATH.'phpsso_server\uploadfile\avatar\\';
							$dir = $avatarfile.$dir1.'\\'.$dir2.'\\'.$phpssouid.'\\';
							if(!file_exists($dir)) {
								mkdir($dir, 0777, true);
							}
							$ext = fileext($_FILES["avatardata"]["name"]);
							//复制文件
							if(move_uploaded_file($_FILES["avatardata"]["tmp_name"],$dir.$phpssouid.'.'.$ext)){
								$avatarurl = APP_PATH.'phpsso_server/uploadfile/avatar/'.$dir1.'/'.$dir2.'/'.$phpssouid.'/'.$phpssouid.'.'.$ext;
								
								$_rurl = $this->avatarthumb($avatarurl,30,30);
								$_rurl = $this->avatarthumb($avatarurl,45,45);
								$_rurl = $this->avatarthumb($avatarurl,90,90);
								$_rurl = $this->avatarthumb($avatarurl,180,180);
								
								$re['success'] = 'OK';
								$re['data'][avatar]= $_rurl;
								$re['msg'] = '头像修改成功~';
								
								$this->ssodb->update(array('avatar'=>1),array('uid'=>$phpssouid));
							}else{
								$re['success'] = 'ERR';
								$re['msg'] = '未知上传错误~';
							}	
						}
					}else{
						$re['success'] = 'ERR';
						$re['msg'] = '图片大小超过限制~';
					}
				}else{
					$re['success'] = 'ERR';
					$re['msg'] = '图片格式不正确~';
				}
			}else{
				$re['success'] = 'NOLOGIN';
				$re['msg'] = '没有登录~';
			}
		}else{
			$re['success'] = 'NODATA';
			$re['msg'] = '参数错误~';
		}
		echo json_encode($re);
	}
	
	/**
	 * 生成头像缩略图函数
	 * @param  $imgurl 图片路径
	 * @param  $width  缩略图宽度
	 * @param  $height 缩略图高度
	 * @param  $autocut 是否自动裁剪 默认裁剪，当高度或宽度有一个数值为0是，自动关闭
	 * @param  $smallpic 无图片是默认图片路径
	 */
	function avatarthumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
		global $image;
		$upload_url = APP_PATH.'phpsso_server/uploadfile/';
		$upload_path = 'phpsso_server/uploadfile/';
		if(empty($imgurl)) return IMG_PATH.$smallpic;
		$imgurl_replace= str_replace($upload_url, '', $imgurl);
		if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
		if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;
		list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
		if($width>=$width_t || $height>=$height_t) return $imgurl;
		$newimgurl = dirname($imgurl_replace).'/'.$width.'x'.$height.'.'.fileext($imgurl_replace);
		//if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
		if(!is_object($image)) {
			pc_base::load_sys_class('image','','0');
			$image = new image(1,0);
		}
		$ra = $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut);
		return $ra ? $upload_url.$newimgurl : $imgurl;
	}	
	
	/**
	 * 注册发送验证码
	 */
	function getsms() {
		$userid = isset($_GET['userid']) ? trim($_GET['userid']) : null;
		$acctoken = isset($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		$mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : null;
		$re = array();
		if($userid && $acctoken && $mobile){
			if($mobile){
				$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
				if($userdata){
					pc_base::load_app_class('smsapi', 'sms', 0); 
					$sms_setting = getcache('sms','sms');
					$sms_setting = $sms_setting[$this->siteid];
					$smsapi = new smsapi($sms_setting['userid'], $sms_setting['productid'], $sms_setting['sms_key']);
					$yzm_code = random(6);//验证码，也是短信唯一码，用于扩展验证
					
					$this->_session_start();
					param::set_cookie('yzm'.$mobile, $yzm_code);

					$msg = "欢迎使用最黔端，你的效验码是：".$yzm_code."。如非本人操作，请忽略本信息。【最黔端】";
					$sent_time = date('Y-m-d H:i:s',SYS_TIME);
					//$smsstatus = $smsapi->send_sms($mobile, $msg, $sent_time,CHARSET,$yzm_code,16);
					
					if(!$smsstatus=="发送成功"){
						$re["success"]="OK";
						$re["data"] = $yzm_code;
						//$re["msg"]="效验码已发送至【$mobile】,请查收短信~";
						$re["msg"]="由于近期短信平台关闭，效验码已经自动填写，请直接提交验证~";
					}else{
						$re["success"]="ERR";
						$re["msg"]="短信获取失败，请重试~";
					}	
				}else{
					$re["success"]="NOLOGIN";
					$re["msg"]="没有登录";
				}
			}else{
				$re["success"]="ERR";
				$re["msg"]="手机号不正确，请重新绑定手机号~";
			}
		}else{
			$re["success"]="NODATA";
			$re["msg"]="参数错误";
		}
		echo json_encode($re);
	}
	
	/**
	 * 注册短信验证
	 */
	function checkcode() {
		$userid = isset($_GET['userid']) ? trim($_GET['userid']) : null;
		$acctoken = isset($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		$mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : null;
		$code = isset($_POST['code']) ? trim($_POST['code']) : null;
		$re = array();
		if($userid && $acctoken && $mobile && $code){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			if($userdata){
				$this->_session_start();
				$yzm = param::get_cookie('yzm'.$mobile);
				if($yzm ==$code){
					$return_id = $this->db->update(array("mobile"=>$mobile),array('userid'=>$userid));
					if($return_id){
						$re["success"]="OK";
						$re["msg"]="绑定成功~";
					}else{
						$re["success"]="ERR";
						$re["msg"]="绑定失败~";
					}
				}else{
					$re["success"]="ERR";
				}
				
				//是否短信提示
				/*
				if($this->config[setting][isregts]){
					pc_base::load_app_class('smsapi', 'sms', 0); //引入smsapi类
					$sms_setting = getcache('sms','sms');
					$sms_setting = $sms_setting[$this->siteid];
					$smsapi = new smsapi($sms_setting['userid'], $sms_setting['productid'], $sms_setting['sms_key']);
					$yzm_code = random(6);//验证码，也是短信唯一码，用于扩展验证
					$msg = "欢迎注册最黔端，你用户名是手机号：".$userdata[username]."，密码是：".$info[password]."。可以登录后修改昵称与头像哦。【最黔端】";
					$sent_time = date('Y-m-d H:i:s',SYS_TIME);
					$smsstatus = $smsapi->send_sms($mobile, $msg, $sent_time,CHARSET,$yzm_code,16); //发送短信
				}
				*/
			}else{
				$re["success"]="NOLOGIN";
				$re["msg"]="绑定失败，没有登录~";
			}
		}else{
			$re["success"]="NODATA";
			$re["msg"]="绑定失败，参数错误~";
		}
		echo json_encode($re);
	}
	
	/**
	 * 用户注册
	 */
	function reg() {
		$re = array();
		$info = array();	
		$info[username] = isset($_REQUEST['username']) ? trim($_REQUEST['username']) : null;
		$info[password] = isset($_REQUEST['password']) ? trim($_REQUEST['password']) : null;
		$info[email] = isset($_REQUEST['email']) ? trim($_REQUEST['email']) : null;
		$info[nickname] = isset($_REQUEST['nickname']) ? trim($_REQUEST['nickname']) : null;

		if($info[username] && $info[password] && $info[email] && $info[nickname]){
			$this->_init_phpsso();
			$status = $this->client->ps_member_register($info['username'], $info['password'], $info['email'], $info['regip']);
			
			if($status > 0) {
				unset($info[pwdconfirm]);
				$info['phpssouid'] = $status;
				$memberinfo = $this->client->ps_get_member_info($status);
				$memberinfo = unserialize($memberinfo);
				$info['encrypt'] = $memberinfo['random'];
				$info['password'] = password($info['password'], $info['encrypt']);
				$info['regdate'] = SYS_TIME;
				$info['lastdate'] = SYS_TIME;
				$info['groupid'] = 2;
				$info[regip] = ip();
				$insert_id = $this->db->insert($info,true);
				
				if($insert_id){
					$userdata = $this->db->get_one(array('userid'=>$insert_id));
					$re[data]=array(
						'userid'=>$userdata[userid],
						'username'=>$userdata[username],
						'password'=>$userdata[password],
						'nickname'=>$userdata[nickname],
						'mobile'=>$userdata[mobile]
					);
					$re["success"]="OK";
					$re["msg"]="注册成功~";
				}else{
					$re["success"]="ERR";
					$re["msg"]="注册失败~";
				}
			} elseif($status == -1) {
				$re["success"]="ERR";
				$re["msg"]="用户名已经存在~";
			} elseif($status == -2) {
				$re["success"]="ERR";
				$re["msg"]="email已存在~";
			} elseif($status == -3) {
				$re["success"]="ERR";
				$re["msg"]="email格式错误~";
			} elseif($status == -4) {
				$re["success"]="ERR";
				$re["msg"]="用户名禁止注册~";
			} elseif($status == -5) {
				$re["success"]="ERR";
				$re["msg"]="邮箱禁止注册~";
			}else {
				$re["success"]="ERR";
				$re["msg"]="注册错误~";
			}
		}else{
			$re["success"]="NODATA";
			$re["msg"]="参数错误~";
		}
		echo json_encode($re);
	}
	
	/**
	 * 修改密码
	 */
	public function editpwd(){
		$data = array();
		$userid = isset($_POST['userid']) ? trim($_POST['userid']) : null;
		$opassword = isset($_POST['opassword']) ? trim($_POST['opassword']) : null;
		$npassword = isset($_POST['npassword']) ? trim($_POST['npassword']) : null;
		
		if($userid && $opassword && $npassword){
			$user = $this->db->get_one(array('userid'=>$userid));
			if($user){
				$_opassword = password($opassword,$user['encrypt']);
				$_npassword = password($npassword,$user['encrypt']);
				if($user['password'] == $_opassword) {
					$return_id = $this->db->update(array("password"=>$_npassword),array('userid'=>$userid));
					if(pc_base::load_config('system', 'phpsso')) {
						//初始化phpsso
						$this->_init_phpsso();
						$res = $this->client->ps_member_edit($user[username], $user[email], $opassword, $npassword, $user['phpssouid'], $user['encrypt']);
						
						if ($res==1 && $return_id) {
							$data["success"]="OK";
							$data["acctoken"]=$_npassword;
							$data["msg"]="修改成功";
						}
					}
				}else{
					$data["success"]="PASSERROR";
					$data["msg"]="原密码输入不正确";
				}
			}else{
				$data["success"]="NOUSER";
				$data["msg"]="没有找到用户";
			}
		}else{
			$data["success"]="NODATA";
			$data["msg"]="没有传入相应参数";
		}
		echo json_encode($data);
	}
        
    public function logout() {
		$setting = pc_base::load_config('system');
		//snda退出
		if($setting['snda_enable'] && param::get_cookie('_from')=='snda') {
			param::set_cookie('_from', '');
			$forward = isset($_GET['forward']) && trim($_GET['forward']) ? urlencode($_GET['forward']) : '';
			$logouturl = 'https://cas.sdo.com/cas/logout?url='.urlencode(APP_PATH.'index.php?m=member&c=index&a=logout&forward='.$forward);
			header('Location: '.$logouturl);
		} else {
			$synlogoutstr = '';//同步退出js代码
			if(pc_base::load_config('system', 'phpsso')) {
				$this->_init_phpsso();
				$synlogoutstr = $this->client->ps_member_synlogout();                        
			}
			param::set_cookie('auth', '');
			param::set_cookie('_userid', '');
			param::set_cookie('_username', '');
			param::set_cookie('_groupid', '');
			param::set_cookie('_nickname', '');
			param::set_cookie('cookietime', '');
			param::set_cookie('_area', '');
			param::set_cookie('_chexi', '');
			$restrstar = '<script type="text/javascript" src="';
			$restrend = '" reload="1"></script>';
			$restr = '';
			$pattern = '/src="(.*?)"/';
			preg_match_all($pattern,$synlogoutstr,$result);
			foreach($result[1] as $r){
				$synurl = @file_get_contents($r); //读取链接
				if (preg_match('/src=/',$synurl)){//检查链接是否含有连接，如果有 打开
					$synurl = str_replace('&quot;','"',$synurl);
					$synurl = str_replace('\\','',$synurl); 
					preg_match_all($pattern,$synurl,$result2);
					foreach($result2[1] as $v){
						$restr .= $restrstar.$v.$restrend;        
					}
				}else{
					$restr .= $restrstar.$r.$restrend;//没有的话使用当前连接
				}
			}
			$arr['success'] = 1;
			$arr['msg'] = iconv("gb2312","UTF-8",$restr);
			echo json_encode($arr);
		}
    }	
	
	private function _session_start() {
		$session_storage = 'session_'.pc_base::load_config('system','session_storage');
		pc_base::load_sys_class($session_storage);
	}
        
	/**
	 * 初始化phpsso
	 * about phpsso, include client and client configure
	 * @return string phpsso_api_url phpsso地址
	 */
	private function _init_phpsso() {
		pc_base::load_app_class('client', 'member', 0);
		define('APPID', pc_base::load_config('system', 'phpsso_appid'));
		$phpsso_api_url = pc_base::load_config('system', 'phpsso_api_url');
		$phpsso_auth_key = pc_base::load_config('system', 'phpsso_auth_key');
		$this->client = new client($phpsso_api_url, $phpsso_auth_key);
		return $phpsso_api_url;
	}

	/**
	 *根据积分算出用户组
	 * @param $point int 积分数
	 */
	protected function _get_usergroup_bypoint($point=0) {
		$groupid = 2;
		if(empty($point)) {
				$member_setting = getcache('member_setting');
				$point = $member_setting['defualtpoint'] ? $member_setting['defualtpoint'] : 0;
		}
		$grouplist = getcache('grouplist');
		
		foreach ($grouplist as $k=>$v) {
				$grouppointlist[$k] = $v['point'];
		}
		arsort($grouppointlist);

		//如果超出用户组积分设置则为积分最高的用户组
		if($point > max($grouppointlist)) {
			$groupid = key($grouppointlist);
		} else {
			foreach ($grouppointlist as $k=>$v) {
				if($point >= $v) {
					$groupid = $tmp_k;
					break;
				}
				$tmp_k = $k;
			}
		}
		return $groupid;
	}
    
	/**
	 * 检查用户名
	 * @param string $username	用户名
	 * @return $status {-4：用户名禁止注册;-1:用户名已经存在 ;1:成功}
	 */
	public function public_checkname($username) {
		
		if(CHARSET != 'utf-8') {
			$username = iconv('utf-8', CHARSET, $username);
			$username = addslashes($username);
		}
		$username = safe_replace($username);
		//首先判断会员审核表
		$this->verify_db = pc_base::load_model('member_verify_model');
		if($this->verify_db->get_one(array('username'=>$username))) {
			return 0;
		}
	
		$this->_init_phpsso();
		$status = $this->client->ps_checkname($username);
			
		if($status == -4 || $status == -1) {
			return 0;
		} else {
			return 1;
		}
	}
	
	/**
	 * 检查用户昵称
	 * @param string $nickname	昵称
	 * @return $status {0:已存在;1:成功}
	 */
	public function public_checknickname_ajax() {
		$nickname = isset($_GET['nickname']) && trim($_GET['nickname']) ? trim($_GET['nickname']) : exit('0');
		if(CHARSET != 'utf-8') {
			$nickname = iconv('utf-8', CHARSET, $nickname);
			$nickname = addslashes($nickname);
		} 
		//首先判断会员审核表
		$this->verify_db = pc_base::load_model('member_verify_model');
		if($this->verify_db->get_one(array('nickname'=>$nickname))) {
			exit('0');
		}
		if(isset($_GET['userid'])) {
			$userid = intval($_GET['userid']);
			//如果是会员修改，而且NICKNAME和原来优质一致返回1，否则返回0
			$info = get_memberinfo($userid);
			if($info['nickname'] == $nickname){//未改变
				exit('1');
			}else{//已改变，判断是否已有此名
				$where = array('nickname'=>$nickname);
				$res = $this->db->get_one($where);
				if($res) {
					exit('0');
				} else {
					exit('1');
				}
			}
 		} else {
			$where = array('nickname'=>$nickname);
			$res = $this->db->get_one($where);
			if($res) {
				exit('0');
			} else {
				exit('1');
			}
		} 
	}
	
	/**
	 * 检查邮箱
	 * @param string $email
	 * @return $status {-1:email已经存在 ;-5:邮箱禁止注册;1:成功}
	 */
	public function public_checkemail_ajax() {
		$this->_init_phpsso();
		$email = isset($_GET['email']) && trim($_GET['email']) ? trim($_GET['email']) : exit(0);
		
		$status = $this->client->ps_checkemail($email);
		if($status == -5) {	//禁止注册
			exit('0');
		} elseif($status == -1) {	//用户名已存在，但是修改用户的时候需要判断邮箱是否是当前用户的
			if(isset($_GET['phpssouid'])) {	//修改用户传入phpssouid
				$status = $this->client->ps_get_member_info($email, 3);
				if($status) {
					$status = unserialize($status);	//接口返回序列化，进行判断
					if (isset($status['uid']) && $status['uid'] == intval($_GET['phpssouid'])) {
						exit('1');
					} else {
						exit('0');
					}
				} else {
					exit('0');
				}
			} else {
				exit('0');
			}
		} else {
			exit('1');
		}
	}
	
	
	/**
	 * 个人中心
	 */
	function my_info() {
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		$re = array();
	
		if($userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			
			$re[data] = $userdata;
			unset($re[data][encrypt]);
			
			$phpssouid = $userdata[phpssouid];
			if($userdata){
				$this->_init_phpsso();
				$ssoinfo = unserialize($this->client->ps_get_member_info($phpssouid));
				if($ssoinfo[avatar]==1){
					$re[data][avatar] = get_memberavatar($phpssouid,'',90);
				}else{
					$re[data][avatar] = '';
				}
				
				if(module_exists('iappTalk')){
					$talkdb = pc_base::load_model('iappTalk_model');
					$re[data][talk] = $talkdb->count(array('userid'=>$userid));
				}
				if(module_exists('iappCoupons')){
					$couponsdb = pc_base::load_model('iappCoupons_data_model');
					$re[data][coupons] = $couponsdb->count(array('userid'=>$userid));
				}
				if(module_exists('iappActivity')){
					$activitydb = pc_base::load_model('iappActivity_data_model');
					$re[data][activity] = $activitydb->count(array('userid'=>$userid));
				}
				
				$iapp_user_bg_db = pc_base::load_model("iapp_user_bg_model");
				$info = $iapp_user_bg_db->get_one(array('userid'=>$userid));
				if($info){
					$re[data][bg] = $info[bg];
				}else{
					$re[data][bg] = '';
				}
				
				$iapp_user_praise_db = pc_base::load_model('iapp_user_praise_model');
				$re[data][praise] = $iapp_user_praise_db->count(array('praise_userid'=>$userid));
				
				$re['success'] = 'OK';
			}else{
				$re['success'] = 'ERR';
			}
		}else{
			$re['success'] = 'ERR';
		}
		echo json_encode($re);
	}
	
	/**
	 * 他人主页
	 */
	function get_user() {
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;

		if($userid){
			$userdata = $this->db->get_one(array('userid'=>$userid));
			$phpssouid = $userdata[phpssouid];
			if($userdata){
				$this->_init_phpsso();
				$ssoinfo = unserialize($this->client->ps_get_member_info($phpssouid));
				if($ssoinfo[avatar]==1){
					$re[data][avatar] = get_memberavatar($phpssouid,'',90);
				}else{
					$re[data][avatar] = '';
				}
				
				$re[data][nickname] = $userdata[nickname];
				$iapp_user_praise_db = pc_base::load_model('iapp_user_praise_model');
				$re[data][praise] = $iapp_user_praise_db->count(array('praise_userid'=>$userid));
	
				$iapp_user_bg_db = pc_base::load_model("iapp_user_bg_model");
				$info = $iapp_user_bg_db->get_one(array('userid'=>$userid));
				if($info){
					$re[data][bg] = $info[bg];
				}else{
					$re[data][bg] = '';
				}
				
				$re['success'] = 'OK';
			}else{
				$re['success'] = 'ERR';
			}
		}else{
			$re['success'] = 'ERR';
		}
		echo json_encode($re);
	}
	
	
	
	/**
	 * 我的优惠券
	 */
	function my_coupons() {
		$re = array();
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		if($userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			if($userdata){
				$c_db = pc_base::load_model('iappCoupons_model');
				$c_data_db = pc_base::load_model('iappCoupons_data_model');
				$data = $c_data_db->select(array('userid'=>$userid), '*','100','`id` DESC');
				if($data){
					$re[data] = $data;
					foreach ($data as $k=>$v) {
						$coupons = $c_db->get_one(array('id'=>$v[couponsid]),'id,catid,title,ltitle,start_time,end_time');
						$coupons[is_time] = $coupons['end_time']>time()? 0:1;
						$coupons[start_time] = date('Y-m-d', $coupons['start_time']);
						$coupons[end_time] = date('Y-m-d', $coupons['end_time']);
						
						
						$re[data][$k][coupons] = $coupons;
					}
					$re['success'] = 'OK';
					$re['msg'] = '数据加载成功~';
				}else{
					$re['success'] = 'ERR';
					$re['msg'] = '没有数据~';
				}
			}else{
				$re['success'] = 'NOLOGIN';
				$re['msg'] = '请先登录~';
			}
		}else{
			$re['success'] = 'ERR';
			$re['msg'] = '参数错误~';
		}
		echo json_encode($re);
	}
	
	/**
	 * 我的活动
	 */
	function my_activity() {
		$re = array();
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		if($userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			if($userdata){
				$activity_db = pc_base::load_model('iappActivity_model');
				$activity_db_data = pc_base::load_model('iappActivity_data_model');
				$data = $activity_db_data->select(array('userid'=>$userid), '*','100','`id` DESC');
				if($data){
					$re[data] = $data;
					foreach ($data as $k=>$v) {
						$activity = $activity_db->get_one(array('id'=>$v[activityid]),'id,title,ltitle,htis,praise,start_time,end_time');
						$activity[is_time] = $activity['end_time']>time()? 0:1;
						$activity[start_time] = date('Y-m-d', $activity['start_time']);
						$activity[end_time] = date('Y-m-d', $activity['end_time']);
						$re[data][$k][activity] = $activity;
						
						$re[data][$k][timeApply] = date('Y-m-d H:m:s', $v['timeApply']);
					}
					$re['success'] = 'OK';
					$re['msg'] = '数据加载成功~';
				}else{
					$re['success'] = 'ERR';
					$re['msg'] = '没有数据~';
				}
			}else{
				$re['success'] = 'NOLOGIN';
				$re['msg'] = '请先登录~';
			}
		}else{
			$re['success'] = 'ERR';
			$re['msg'] = '参数错误~';
		}
		echo json_encode($re);
	}
	
	/**
	 * 签到
	 */
	function integral() {
		$re = array();
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		if($userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			if($userdata){
				
				$pay_account_db = pc_base::load_model("pay_account_model");
				
				$d = date('Y-m-j',time());
				$start_time = strtotime($d.' 00:00:00');
				$end_time = strtotime($d.' 23:59:59');
				
				$pay_account = $pay_account_db->select("`userid` = '$userid' AND '$start_time'<= `addtime` AND `addtime`<='$end_time'");
				if($pay_account){
					$re['success'] = 'EXIST';
					$re['msg'] = "亲，你今天已经签到哦~";
					$re['data'][integral] = $userdata['point'];
					$re['data'][tom] = '1';
				}else{
					$flag = 'iapp_'.$userdata['userid'].'_'.time();
					$presentpoint = 1;			
					pc_base::load_app_class('receipts','pay',0);
					receipts::point($presentpoint,$userdata['userid'], $userdata['username'], $flag,'selfincome','签到奖励积分',$userdata['username']);

					$re['success'] = 'OK';
					$re['msg'] = "签到成功，获得".$presentpoint."个黔币~";
					$re['data'][integral] = $userdata['point']+$presentpoint;
					$re['data'][tom] = '1';
				}
			}else{
				$re['success'] = 'NOLOGIN';
				$re['msg'] = '请先登录~';
			}
		}else{
			$re['success'] = 'ERR';
			$re['msg'] = '参数错误~';
		}
		echo json_encode($re);
	}
	
	/**
	 * 赞
	 */
	function user_praise() {
		$re = array();
		$praise_userid = trim($_GET['praise_userid']) ? intval(trim($_GET['praise_userid'])) : null;
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		if($praise_userid && $userid && $acctoken){
			$userdata = $this->db->get_one(array('userid'=>$userid,'password'=>$acctoken));
			if($userdata){
				$iapp_user_praise_db = pc_base::load_model("iapp_user_praise_model");
				
				$d = date('Y-m-j',time());
				$start_time = strtotime($d.' 00:00:00');
				$end_time = strtotime($d.' 23:59:59');
				$praisedata = $iapp_user_praise_db->select("`userid` = '$userid' AND `praise_userid` = '$praise_userid' AND '$start_time'<= `addtime` AND `addtime`<='$end_time'");
				if(!$praisedata){
					$return_id = $iapp_user_praise_db->insert(array('userid'=>$userid,'username'=>$userdata[username],'nick'=>$userdata[nickname],'praise_userid'=>$praise_userid,'praise'=>'1','addtime'=>time()),'1');
					$praise_count = $iapp_user_praise_db->count(array('praise_userid'=>$praise_userid));
					if($return_id){
						$re[success]="OK";
						$re[msg]="赞成功";
						$re[data][praise]=$praise_count;
					}else{
						$re[success]="ERR";
						$re[msg]="赞失败";
					}
				}else{
					$re[success] = 'ERR';
					$re[msg] = "你已经暂过,24小时后才能再赞~";
				}
			}else{
				$re[success]="NOLOGIN";
				$re[msg]="没有登录";
			}
		}else{
			$re[success]="ERR";
			$re[msg]="参数错误";
		}
		echo json_encode($re);
	}
	
	/**
	*用户主页背景
	*/
	function set_user_bg() {
		$re = array();
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		if($userid && $acctoken){
			$photos = $this->upload('photos','jpg|jpeg|gif|png');
			$_bg = $photos[0][filepath] !=''? $photos[0][filepath]:'';
			$_bg = $this->upload_url.$_bg;
			$_bg = thumb($_bg,720,0);
			$iapp_user_bg_db = pc_base::load_model("iapp_user_bg_model");
			$info = $iapp_user_bg_db->get_one(array('userid'=>$userid));
			if($info){
				$iapp_user_bg_db->update(array('bg'=>$_bg),array('userid'=>$userid));
			}else{
				$return_id = $iapp_user_bg_db->insert(array('userid'=>$userid,'bg'=>$_bg),'1');
			}
			$re[success]="OK";
			$re[data][bg]=$_bg;
			$re[msg]="背景修改成功~";
		}else{
			$re[success]="ERR";
		}
		echo json_encode($re);
	}

	/**
	 * 常规上传
	 */
	function upload($file,$ext) {
		pc_base::load_sys_class('attachment','',0);
		$siteinfo = getcache('sitelist', 'commons');
		$site_setting = string2array($siteinfo[$this->siteid]['setting']);
		$attachment = new attachment('iappTalk',0,$this->siteid);
		$attachment->set_userid(1);
		$a = $attachment->upload($file,$ext,$site_setting['upload_maxsize']*1024,0,array(),0);
		return $attachment->uploadedfiles;
	}
	
	/**
	 * 删除背景
	 */
	function del_user_bg() {
		$re = array();
		$userid = trim($_GET['userid']) ? intval(trim($_GET['userid'])) : null;
		$acctoken = trim($_GET['acctoken']) ? trim($_GET['acctoken']) : null;
		if($userid && $acctoken){
			$iapp_user_bg_db = pc_base::load_model("iapp_user_bg_model");
			$info = $iapp_user_bg_db->delete(array('userid'=>$userid));
			$re[success]="OK";
			$re[msg]="背景删除成功~";
		}else{
			$re[success]="ERR";
			$re[msg]="参数错误~";
		}
		echo json_encode($re);
	}
	
	/**
	 * 找回密码 
	 */
	public function forget_password () {
		
		$email_config = getcache('common', 'commons');
		
		//SMTP MAIL 二种发送模式
 		if($email_config['mail_type'] == '1'){
			if(empty($email_config['mail_user']) || empty($email_config['mail_password'])) {
				showmessage(L('email_config_empty'), HTTP_REFERER);
			}
		}
		$this->_session_start();
		$member_setting = getcache('member_setting');
		if(isset($_POST['dosubmit'])) {
			if ($_SESSION['code'] != strtolower($_POST['code'])) {
				showmessage(L('code_error'), HTTP_REFERER);
			}
			
			$memberinfo = $this->db->get_one(array('email'=>$_POST['email']));
			if(!empty($memberinfo['email'])) {
				$email = $memberinfo['email'];
			} else {
				showmessage(L('email_error'), HTTP_REFERER);
			}
			
			pc_base::load_sys_func('mail');
			$phpcms_auth_key = md5(pc_base::load_config('system', 'auth_key').$this->http_user_agent);

			$code = sys_auth($memberinfo['userid']."\t".SYS_TIME, 'ENCODE', $phpcms_auth_key);

			$url = APP_PATH."index.php?m=member&c=index&a=public_forget_password&code=$code";
			$message = $member_setting['forgetpassword'];
			$message = str_replace(array('{click}','{url}'), array('<a href="'.$url.'">'.L('please_click').'</a>',$url), $message);
			//获取站点名称
			$sitelist = getcache('sitelist', 'commons');
			
			if(isset($sitelist[$memberinfo['siteid']]['name'])) {
				$sitename = $sitelist[$memberinfo['siteid']]['name'];
			} else {
				$sitename = 'PHPCMS_V9_MAIL';
			}
			sendmail($email, L('forgetpassword'), $message, '', '', $sitename);
			showmessage(L('operation_success'), 'index.php?m=member&c=index&a=login');
		} elseif($_GET['code']) {
			$phpcms_auth_key = md5(pc_base::load_config('system', 'auth_key').$this->http_user_agent);
			$hour = date('y-m-d h', SYS_TIME);
			$code = sys_auth($_GET['code'], 'DECODE', $phpcms_auth_key);
			$code = explode("\t", $code);

			if(is_array($code) && is_numeric($code[0]) && date('y-m-d h', SYS_TIME) == date('y-m-d h', $code[1])) {
				$memberinfo = $this->db->get_one(array('userid'=>$code[0]));
				
				if(empty($memberinfo['phpssouid'])) {
					showmessage(L('operation_failure'), 'index.php?m=member&c=index&a=login');
				}
				$updateinfo = array();
				$password = random(8);
				$updateinfo['password'] = password($password, $memberinfo['encrypt']);
				
				$this->db->update($updateinfo, array('userid'=>$code[0]));
				if(pc_base::load_config('system', 'phpsso')) {
					//初始化phpsso
					$this->_init_phpsso();
					$this->client->ps_member_edit('', $email, '', $password, $memberinfo['phpssouid'], $memberinfo['encrypt']);
				}
	
				showmessage(L('operation_success').L('newpassword').':'.$password);

			} else {
				showmessage(L('operation_failure'), 'index.php?m=member&c=index&a=login');
			}

		} else {
			$siteid = isset($_REQUEST['siteid']) && trim($_REQUEST['siteid']) ? intval($_REQUEST['siteid']) : 1;
			$siteinfo = siteinfo($siteid);
			
			include template('member', 'forget_password');
		}
	}
	
}
?>